package com.wslNB.goods.service.impl;


import com.alibaba.fastjson.JSON;
import com.wslNB.goods.dao.*;
import com.wslNB.goods.pojo.*;
import com.wslNB.goods.service.SpuService;
import com.wslNB.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品接口
 */
@Service
@Transactional //加入事务控制
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    CategoryBrandMapper categoryBrandMapper;


    /**
     * 添加商品
     *
     * @param goods
     */
    @Override
    public void addSpu(Goods goods) {
        //新增spu
        Spu spu = goods.getSpu();
        long nextId = idWorker.nextId();
        spu.setId(String.valueOf(nextId));//设置主键id
        spu.setIsDelete("0");//是否删除，0未删除
        spu.setIsMarketable("0");//是否上架，0未上架
        spu.setStatus("0");//审核状态，0未审核
        spuMapper.insert(spu);

        //新增sku审核表
        saveSkuList(goods);
    }


    /**
     * 保存sku列表
     *
     * @param goods
     */
    private void saveSkuList(Goods goods) {

        Date date = new Date();
        Spu spu = goods.getSpu();
        //根据spu中的三级分类id获取分类实体
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        //根据spu中的品牌id获取品牌实体
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        //添加分类和品牌添加到tb_category_brand表中
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(brand.getId());
        categoryBrand.setCategoryId(category.getId());
        //根据当前分类id和品牌id查询是否已经存在
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count == 0) {
            categoryBrandMapper.insert(categoryBrand);
        }


        //1.获取sku
        List<Sku> skuList = goods.getSkuList();
        if (!skuList.isEmpty()) {
            for (Sku sku : skuList) {
                //1.设置sku主键
                sku.setId(String.valueOf(idWorker.nextId()));
                //2.设置spec规格
                if (sku.getSpec() == null || "".equals(sku.getSpec())) {
                    sku.setSpec("{}");
                }
                /*
                     3.设置sku的名称，sku名称=spu名称+规格
                     spe={'颜色': '红色', '版本': '8GB+128GB'}
                    第一次遍历 name=spu名称 红色
                    第二次遍历 name= spu名称 红色 8GB+128GB
                 */
                String name = spu.getName();
                Map<String, String> map = JSON.parseObject(sku.getSpec(), Map.class);
                if (map != null || map.size() > 0) {
                    for (String value : map.values()) {
                        name += " " + value;
                    }
                }
                sku.setName(name);
                //4.设置spuId
                sku.setSpuId(spu.getId());
                //5.设置时间
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                //6.设置分类id和分类名称，注意该分类是spu表中的三级分类id获取的
                sku.setCategoryId(category.getId());
                sku.setCategoryName(category.getName());
                //7.设置品牌名称
                sku.setBrandName(brand.getName());
                //8.循环添加sku
                skuMapper.insertSelective(sku);//保存一个实体，null的属性不会保存，会使用数据库默认值

            }
        }
    }


    /**
     * 根据spuID查询
     * @param id
     * @return
     */
    @Override
    public Goods findById(String id) {
        //获取spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",spu.getId());
        //通过spuId查询sku
        List<Sku> skus = skuMapper.selectByExample(example);
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skus);
        //返回数据
        return goods;
    }


    /**
     * 修改商品信息
     * @param goods
     * @return
     */
    @Override
    public void update(Goods goods) {

        //修改spu
        spuMapper.updateByPrimaryKeySelective(goods.getSpu());
        //修改sku
        List<Sku> skuList = goods.getSkuList();
        //对skulist删除后重新添加
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",goods.getSpu().getId());
        skuMapper.deleteByExample(example);
        //添加skuList
        saveSkuList(goods);
    }


    /**
     * 审核商品
     *      判断商品是否存在
     *      判断商品是否被删除
     *    修改审核状态--自动上架
     * @param id
     */
    @Override
    public void audit(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //商品存在
        if(spu==null){
            throw new RuntimeException("商品不存在");
        }
        //查看删除状态
        if("1".equals(spu.getIsDelete())){
            throw new RuntimeException("商品已被删除");
        }
        //审核通过
        spu.setStatus("1");
        //自动上架
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品下架
     * 商品的逻辑删除
     * @param id
     */
    @Override
    public void pull(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否存在
        if(spu==null){
            throw new RuntimeException("下架失败，该商品不存在");
        }
        if("1".equals(spu.getIsDelete())){
            throw new RuntimeException("下架失败，该商品已被删除");
        }
        spu.setIsMarketable("0");//修改下架信息
        spu.setStatus("0");//修改审核状态
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品上架
     * @param id
     */
    @Override
    public void put(String id) {

        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断该商品是否通过审核
        if("0".equals(spu.getStatus())){
            throw new RuntimeException("上架失败，未审核");
        }
        spu.setIsMarketable("1");
        spu.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品的逻辑删除
     * @param id
     */
    @Override
    public void delete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断是否重复删除
        if("1".equals(spu.getIsDelete())){
            throw new RuntimeException("商品已被删除");
        }
        spu.setIsDelete("1");//删除
        spu.setIsMarketable("0");//上架
        spu.setStatus("0");//审核
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品的还原
     * @param id
     */
    @Override
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if("0".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品未被删除");
        }
        spu.setIsDelete("0");
        spu.setStatus("0");
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品的持久化物理删除
     * @param id
     */
    @Override
    public void realDelete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品未被逻辑删除");
        }
        spuMapper.deleteByPrimaryKey(spu);
        
    }


}
